
package mypackage;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 //import java.io.InputStream;	//FD 13-11-12
import java.io.OutputStreamWriter;
import java.util.Random;


import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Form;
import javax.microedition.location.*;
import net.rim.device.api.ui.component.ButtonField; 
//import net.rim.device.api.command.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BasicEditField;


/**
 * This application acts as a simple travel computer, recording route
 * coordinates, speed and altitude. Recording begins as soon as the
 * application is invoked.
 */
public final class GPSScreen extends UiApplication implements FieldChangeListener, Runnable  
{
    // Represents the number of updates over which altitude is calculated, in seconds
  //  private static final int GRADE_INTERVAL = 5;   //FD 13-11-12
  //  private static final long ID = 0x5d459971bb15ae7aL; //FD 13-11-12    
    private int CantidadAct;
    // Represents period of the position query, in seconds
    private static int _interval = 1;
    private double _latitude;
    private double _longitude;    
 //   private double _altitud;    //FD 13-11-12
    
    private LocationProvider _locationProvider;
    private GPSDemoScreen _screen;
  //  private GPSDemoScreen objScreenGPS;	//FD 13-11-12
    //private MapView _mapview = new MapView();    
    public LabelField Label;
    public LabelField cantLat = new LabelField();
    public  LabelField textAltitud = new LabelField();
    public LabelField textVelocidad = new LabelField();
    public LabelField textLat = new LabelField();
    public LabelField textLong = new LabelField();
    public LabelField textImei = new LabelField();
    public LabelField textCourse = new LabelField();
    public float _course;
    public float _speed ;
    // private InputStream _in;	//FD 13-11-12
    private OutputStreamWriter _out;
    private String imei = GPRSInfo.imeiToString(GPRSInfo.getIMEI(), true);  
    
    public String strTimeSender=null;
    
    //public BasicEditField  buttonf = new BasicEditField("Put your E-Mail: ","",35 , BasicEditField.FILTER_EMAIL);

    //////////////
    public BasicEditField  buttonEditFieldTime = new BasicEditField("TimeSender(1-50000 seconds): ","",5 , BasicEditField.FILTER_INTEGER);
    public ButtonField  buttonTime = new ButtonField("Submit",ButtonField.CONSUME_CLICK);
    /////////////    
    public BasicEditField  strImeiField = new BasicEditField("USER ID: " + GPRSInfo.imeiToString(GPRSInfo.getIMEI(),true),"",5 , 
    		Field.FIELD_BOTTOM|BasicEditField.READONLY);
    public BasicEditField strCodAct= null;
    private String strCodActUser=null;
    /////////////
    public ButtonField  buttonsubmit = new ButtonField("Submit",ButtonField.CONSUME_CLICK|Field.FIELD_RIGHT);
    /////////////
    
    public int bFlagINGRESO=0;
    //public Command cmdSubmit;
    public Thread t;
    public FieldChangeListener listener=null;
    
    public Form mForm;
    //private Display mDisplay;
    ///////////////////////////////////Archivos y directorios//////////////////////////////////////////////////
   // public String path="file:///store/samples/CYS/";
    //public String path="file:///SDCard/BlackBerry/CYS/";      
    //public String path="file:///CFCard/newfile.tx";
    //public String path="file:///Device/";
    public String path=System.getProperty("fileconn.dir.photos")+"cys/";
    public String strNameFileCode="cystem.txt";
    public String strNameFileTime="cystime.txt";
    public String strDirPrincPic="principal.png";
    
    // ApplicationPermissions permissions = new ApplicationPermissions();
//
    public int inGlobalTime=0;
    
    //private VerticalFieldManager objManager;
    //private HorizontalFieldManager objManagerH;
    //public HorizontalFieldManager objManagerH = new HorizontalFieldManager(HorizontalFieldManager.USE_ALL_WIDTH |HorizontalFieldManager.USE_ALL_HEIGHT){
    
    private Bitmap               objBitmap;
    
////////////////################################################################################///////////////////
////////////////################################################################################///////////////////
////////////////############################## APLICATION ##################################################///////////////////
    
    public static void main(String[] args)
    {
    	 System.out.println("[main] DEBUG: Main"); 
    	 
    	GPSScreen theApp = new GPSScreen();       
        theApp.enterEventDispatcher();
        
        new GPSScreen().enterEventDispatcher();
    }
    public GPSScreen()
    {	   	
    	
    	super();    	
    	System.out.println("[GPSScreen] DEBUG: GPSScreen");
    	
       _screen = new GPSDemoScreen();       
        _screen.setTitle("iPosition CYS");
        //_screen.add(new RichTextField("Bienvenido!"));       
        ////////////////////////////////////////// BITMAP PRINCIPAL //////////////////////////////////////////////////////////          
        	//////////
                
       final Bitmap objBitmap1 = Bitmap.getBitmapResource( strDirPrincPic);
       		 
        	VerticalFieldManager objManagerV = null;
        	
        	objManagerV = new VerticalFieldManager(
        			Manager.FOCUSABLE
        			//|Manager.HORIZONTAL_SCROLL
        			//|Manager.HORIZONTAL_SCROLLBAR
        			|Manager.VERTICAL_SCROLL
        			|Manager.VERTICAL_SCROLLBAR
        			|Manager.USE_ALL_WIDTH 
        			|Manager.USE_ALL_HEIGHT)
        	{
        	         protected void paint( Graphics g ){

        	        	int y = this.getManager().getVerticalScroll();
        	        	
        	        	int hy = this.getManager().getScreen().getHeight();
        	        	int hx=this.getManager().getScreen().getWidth();
        	        	int HeigthScreen=0;
        	        	int widthScreen=0;
        	        	
        	        	System.out.println("[GPSScreen] WIDHT Screen: "+String.valueOf(hx)+" Height Screen: "+String.valueOf(hy)+" \n");
        	        	
        	        	if(hy<objBitmap1.getHeight())
        	        	{        	        		
        	        		HeigthScreen=objBitmap1.getHeight()+40;
        	        	}else if(hy==objBitmap1.getHeight())
        	        	{
        	        		HeigthScreen=hy+40;        	        		
        	        	}else
        	        	{
        	        		HeigthScreen=hy+20;
        	        	}
        	        	////////////////////////////////////
        	        	if(hx<objBitmap1.getWidth())
        	        	{        	        		
        	        		widthScreen=objBitmap1.getWidth()+40;
        	        		//System.out.println("[GPSScreen] WIDHT: "+String.valueOf(objBitmap1.getWidth())+" Height: "+String.valueOf(objBitmap1.getHeight())+" \n");
    	                    
        	        		
        	        	}else if(hx==objBitmap1.getHeight())
        	        	{
        	        		widthScreen=hx+20;        	        		
        	        	}else
        	        	{
        	        		widthScreen=hx+10;
        	        	}        	        	
        	        	////////////
        	        	System.out.println("[GPSScreen] WIDHT NEWScreen: "+String.valueOf(widthScreen)+" Height NEWScreen: "+String.valueOf(HeigthScreen)+" \n");
        	        	setExtent( widthScreen, HeigthScreen);
        	        	/////////////////////////////////////////////
        	        	/*
	                    Bitmap NBitmap;
	                    if(hy>hx)
	                    {
	                    	System.out.println("[GPSScreen] HY> hx: "+String.valueOf(hx)+" hy: "+String.valueOf(hy)+" \n");
	                    	//
	                    	//NBitmap = new Bitmap(hx-40,hy-40);
	                    	NBitmap = new Bitmap(hx,hy);
	                    	// Bitmap NBitmap = new Bitmap(200,150);
	                    }else
	                    {
	                    	 
	                    	System.out.println("[GPSScreen] HX> hx: "+String.valueOf(hx)+" hy: "+String.valueOf(hy)+" \n"); 
	                    	//setExtent( hx, hy+100);
	                    	NBitmap = new Bitmap(hx,hy);
	                    	//NBitmap = new Bitmap(hx-40,hy-40);
	                    	// Bitmap NBitmap = new Bitmap(200,150);
	                    }
	                    */
	                  
	                    //objBitmap1.scaleInto(NBitmap, Bitmap.FILTER_BILINEAR, Bitmap.SCALE_TO_FIT);		//SI QUIERO CAMBIAR TAMAÑO
	                
	                    
	                    System.out.println("[GPSScreen] WIDHT Image: "+String.valueOf(objBitmap1.getWidth())+" Height Image: "+String.valueOf(objBitmap1.getHeight())+" \n");
	                    //System.out.println("[GPSScreen] WIDHT: "+String.valueOf(NBitmap.getWidth())+" Height: "+String.valueOf(NBitmap.getHeight())+" \n");
	                    
	                   // g.drawBitmap( 0, y, 180, 100, objBitmap1, 0, 0 );
	                    
	                    //g.drawBitmap( 0, y, NBitmap.getWidth(), NBitmap.getHeight(), NBitmap, 0, 0 );
	                    g.drawBitmap( 0, y, objBitmap1.getWidth(), objBitmap1.getHeight(), objBitmap1, 0, 0 );
	                    
	                    super.paint( g );
        	         }
            };
            
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////

            
            strCodActUser=ReadFile(path,strNameFileCode);

    		if((strCodActUser==null)||(strCodActUser==""))
    		{
    			Random rd=new Random();
    			strCodActUser=String.valueOf(rd.nextInt(1000000));				
    			strCodActUser="CYS"+strCodActUser;
    			
            	strCodAct=new BasicEditField("CODE ID: " +strCodActUser,"",5 , BasicEditField.READONLY|Field.FIELD_BOTTOM);
            	saveFile(path,strNameFileCode,strCodActUser);
            	
            	System.out.println("[GPSScreen] CODIGO ACTIVACION CREADO: "+ strCodActUser +"\n");
            	
            	buttonsubmit.setChangeListener(this);
            	
            	/*
            	_screen.add(strImeiField);
            	_screen.add(strCodAct);
    	        _screen.add(buttonsubmit);
    	        */
    	       
            	
            	objManagerV.add(strImeiField);
    	        objManagerV.add(strCodAct);
    	        objManagerV.add(buttonsubmit);
    	        
                _screen.add(objManagerV);		//VERIFICAR
                
    	        pushScreen(_screen);  
    	        
    		}else
    		{
    			strCodAct=new BasicEditField("CODE ID: " +strCodActUser,"",5 , BasicEditField.READONLY|Field.FIELD_BOTTOM);
    			
    			buttonsubmit.setChangeListener(this);
    			/*
            	_screen.add(strImeiField);
            	_screen.add(strCodAct);
    	        _screen.add(buttonsubmit);
    	        */
    			
    	        objManagerV.add(strImeiField);
    	        objManagerV.add(strCodAct);
    	        objManagerV.add(buttonsubmit);
    	        
                _screen.add(objManagerV);		//VERIFICAR
                
    	        pushScreen(_screen);  
    		}
         
    }
    
    public void TimeScreen()
    {
    	
    	System.out.println("[TimeScreen] DEBUG: TimeScreen");
    	
    	//_screen = new GPSDemoScreen();
    	
    	strTimeSender=ReadFile(path,strNameFileTime);
    	
    	if(strTimeSender==null)
    	{
    		System.out.println("[TimeScreen] DEBUG: strTimeSender es null \n");
    		
    	 	_screen.deleteAll();
    	 	
    	 	_screen.setTitle("iPosition CYS");
    	 	
			_screen.add(buttonEditFieldTime);
			
			buttonTime.setChangeListener(this);
			
			_screen.add(buttonTime);
			
			System.out.println("[TimeScreen] DEBUG: pushScreen time \n");
			 pushScreen(_screen);
			 
			 
    	}else
    	{
    		System.out.println("[TimeScreen] DEBUG: YA EXISTE TIEMPO DE ENVIO EN FILE");
    		bFlagINGRESO=1;
    		UiApplication.getUiApplication().invokeLater(this);		//ACTIVAR	//EMPIEZA APLICACION
    		
    	}
    	
    }

	public void run() {
		System.out.println("[run] DEBUG: APP RUN"); 

		try
	        {
		      if(startLocationUpdate())
		        {	   
		            _screen.setState(_locationProvider.getState());
		        }
	        }catch(Exception ex)
	        {
	        	 System.out.println("[run] DEBUG: ERROR: "+ex);
	        }
			
			System.out.println("[run] DEBUG: pushScreen _screen");
			pushScreen(_screen);  		//ESTo lo hace funcionar osea aparece la pantalla
		
	}
  
////#########################################################################################################//
/////////////////////////// NO UTILIZADO - USANDO HANDLE ///////////////////////////////////////////////////////////////////////////////////
	public void fieldChanged(Field field, int context) {
		System.out.println("[fieldChanged] DEBUG: FIELD CHANGED"); 
		
		if (field == buttonsubmit) //if second button selected
        {		  	
        		TimeScreen();

        }else if(field == buttonTime)
        {
        	if((buttonEditFieldTime.isDataValid())&&(buttonEditFieldTime.getText()!=null)&&(buttonEditFieldTime.getText()!=""))
            {
        		strTimeSender=buttonEditFieldTime.getText();        		
        		System.out.println("[fieldChanged] Email: "+strTimeSender+"\n");        		
        		Dialog.alert("Time Sender: "+strTimeSender); //show text from second input field       		
        		
        		saveFile(path,strNameFileTime,strTimeSender);
        		bFlagINGRESO=1;
        		UiApplication.getUiApplication().invokeLater(this);		//ACTIVAR	//EMPIEZA APLICACION
            }else
            {
            	System.out.println("[fieldChanged] Ingreso de tiempo incorrecto\n");
        		Dialog.alert("DEBE INGRESAR EL TIEMPO DE ENVIO CORRECTAMENTE!"); //show text from second input field
            }
        }
		
	}
	
	  private final class GPSDemoScreen extends MainScreen
	    {
	    	
	        TextField _statusTextField;
	        
	        GPSDemoScreen()
	        {   
	            // Initialize UI
	            _statusTextField = new TextField(Field.NON_FOCUSABLE);
	            System.out.println("[GPSDemoScreen] Pase por aca \n");
	        }

	        /**
	         * Display the state of the GPS service
	         * 
	         * @param newState The state to display
	         */
	        public void setState(final int newState)
	        {
	            UiApplication.getUiApplication().invokeLater(new Runnable()
	            {
	                public void run()
	                {
	                	System.out.println("[GPSDemoScreen-setState - run]  Run - new state \n");
	                	
	                    switch(newState)
	                    {
	                        case LocationProvider.AVAILABLE:
	                            _statusTextField.setText("Available");
	                            System.out.println("[GPSDemoScreen-setState - run] Location Available \n");
	                            break;
	                        case LocationProvider.OUT_OF_SERVICE:
	                            _statusTextField.setText("Out of Service");
	                            System.out.println("[GPSDemoScreen-setState] Location Out of Service \n");
	                            break;
	                        case LocationProvider.TEMPORARILY_UNAVAILABLE:
	                            _statusTextField.setText("Temporarily Unavailable");
	                            System.out.println("[GPSDemoScreen-setState] Location Unavailable \n");
	                            break;
	                    }
	                    
	                    
	                }
	            });
	        }

	        public void close()
	        {
	            if(_locationProvider != null)
	            {
	                _locationProvider.reset();
	                _locationProvider.setLocationListener(null, -1, -1, -1);
	                System.out.println("[GPSDemoScreen-Close] Location Close \n");
	            }

	            super.close();
	        }
	    }
	  
	///////////////////////////////////////////////////////////////GPS ETAPA /////////////////////////////
	//////////////////////###################################################################################////////////////
	
	public boolean startLocationUpdate() throws Exception
    {    	
       //TextField _statusTextField = new TextField("1","PASE");
		
		 System.out.println("[startLocationUpdate] Start \n");
        try
        {	
        	// _statusTextField.setText("PASEEEEEEEE!");
	      //  if(!(GPSInfo.getDefaultGPSMode() == GPSInfo.GPS_MODE_NONE))
	            try
	            {
	                Criteria criteria = new Criteria();
	               //criteria.setHorizontalAccuracy(25); // 25m
	               // criteria.setVerticalAccuracy(25); 
	                criteria.setCostAllowed(false);
	
	                _locationProvider = LocationProvider.getInstance(criteria);

	                if(_locationProvider != null)
	                {
						_locationProvider.setLocationListener(new LocationListenerImpl(), _interval, -1, -1);
						System.out.println("[startLocationUpdate] LocationProviderStart Listener \n");               
	                }
	                else
	                {
	                    invokeLater(new Runnable()
	                    {
	                        public void run()
	                        {
	                           // Dialog.alert("Failed to obtain a location provider, exiting...");
	                            System.exit(0);
	                        }
	                    });
	                    return false;	//?esta de mas
	                }
	            }
	            catch(final LocationException le)
	            {
	                invokeLater(new Runnable()
	                {
	                    public void run()
	                    {
	                       // Dialog.alert("Failed to instantiate LocationProvider object, exiting..." + le.toString());
	                        System.exit(0);
	                    }
	                });
	            }
	        	
	           /*
	             invokeLater(new Runnable()
	            
	            {
	                public void run()
	                {
	                    Dialog.alert("GPS is not supported on this device, exiting...");
	                    System.exit(0);
	                }
	            });           
	       		*/
	       
        }catch(Exception ex)
        {
        	//System.exit(0);
        	
				throw ex;      	
        }
        return true;
    }
	public class DatosGPS
	{
		double dbLatitud=0;
    	double dbLongitud=0;
    	double dbAltitud=0;
    	float fCourse=0;
    	float fSpeed=0;	
    	String strCodAct;
	}
    public class LocationListenerImpl implements LocationListener
    {
        public void locationUpdated(LocationProvider provider, Location location)
        {        	
        	DatosGPS objDatosGPS = new DatosGPS();
        	
            if(location.isValid())
            {
            	if(bFlagINGRESO==1)
    	        {
    	        	System.out.println("DEBUG: Location");
    	        	objDatosGPS.dbLongitud = location.getQualifiedCoordinates().getLongitude();
    	        	objDatosGPS.dbLatitud = location.getQualifiedCoordinates().getLatitude();
    	        	objDatosGPS.dbAltitud=location.getQualifiedCoordinates().getAltitude(); 
    	        	objDatosGPS.fCourse = location.getCourse();
    	        	objDatosGPS.fSpeed = location.getSpeed();
                    objDatosGPS.strCodAct= strCodActUser;
    	        	
                    System.out.println("DEBUG: Long:"+_longitude);
                    System.out.println("DEBUG: Long:"+_latitude);
                    updateCoordinates(objDatosGPS);
                   //_mapview.setZoom(Integer.parseInt("0.1"));
                  
                    
    	        }else
	            {
	            	System.out.println("DEBUG: NO INGRESE");
	            	
	            }
            }
        }

        public void providerStateChanged(LocationProvider provider, int newState)
        {
            if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
            {
                provider.reset();
            }
            _screen.setState(newState);
        }
    }
    public void updateCoordinates(final DatosGPS objDatosGPSUpdate)
    {
    	System.out.println("DEBUG: UpdateCoordinates:");
    	//dLatitud = LocationData.getQualifiedCoordinates().getLongitude();
    	  UiApplication.getUiApplication().invokeLater(new Runnable()
          {
              /**
               * @see java.lang.Runnable#run()
               */
              public void run()
              { 
            	  	textLat.setText("Latitud = "+objDatosGPSUpdate.dbLatitud);
			        textLong.setText("Longitud = "+objDatosGPSUpdate.dbLongitud);
			        textAltitud.setText("Altitud = "+objDatosGPSUpdate.dbAltitud);
			        textCourse.setText("Curso = "+objDatosGPSUpdate.fCourse);
			        textVelocidad.setText("Velocidad = "+objDatosGPSUpdate.fSpeed);
			        cantLat.setText("Cantidad de Act ="+CantidadAct);
			       
			       _screen.deleteAll();
			       _screen.setTitle("iPosition CYS");
					//_screen.add(cantLat);
					_screen.add(textCourse);
					_screen.add(textAltitud);
					 _screen.add(textVelocidad);
					 _screen.add(textLat);
					 _screen.add(textLong);
					 _screen.add(textImei);
					 
					 pushScreen(_screen);
					 
					 if((_latitude!=0)&&(_longitude!=0))
		            {	
						 StreamConnection connection = null; 
						 try
					        {
					            //_screen.updateDisplay("Opening Connection...");							  
					            //String url = "socket://190.18.128.130 :5123;deviceside=true";                                    
							    String url = "socket://sharedpc.dnsalias.com:5123;deviceside=true";
					            connection = (StreamConnection)Connector.open(url);
					            System.out.println("DEBUG: conectado");
					           // _in = connection.openInputStream();
					            
					            _out = new OutputStreamWriter(connection.openOutputStream());            
					           // StringBuffer test = new StringBuffer();
					     		  String test = "{"
					   				  		+ "\"Id\":\""+"BB"+"\","
					   				  		+ "\"Lat\":\""+String.valueOf(objDatosGPSUpdate.dbLatitud)+"\","
					   				  		+ "\"Lng\":\""+String.valueOf(objDatosGPSUpdate.dbLongitud)+"\","
					   				  		+ "\"Alt\":\""+String.valueOf(objDatosGPSUpdate.dbAltitud)+"\","
					   				  		+ "\"Spe\":\""+String.valueOf(objDatosGPSUpdate.fSpeed)+"\","						
					   				  		+ "\"IMEI\":\""+imei+"\","
					   				  		+ "\"CodAct\":\""+objDatosGPSUpdate.strCodAct+"\","
					   				  		+ "\"Batt\":\""+DeviceInfo.getBatteryLevel()+"\""
					   				  		//+ "\"Batt\":\""+DeviceInfo.getBatteryStatus()+"\""
					   		  				+ "}";
					     		 
					     		 
					     		 
					     		  System.out.println("DEBUG: OUTS: "+ test);
					            _out.write(test);
					            _out.flush();
					            System.out.println("DEBUG: enviado");
					        }
					        catch(IOException e)
					        {
					            System.err.println(e.toString());
					        }
						 	finally
					        {              
					            try
					            {       
					                _out.close();
					            }
					            catch(IOException ioe)
					            {               
					            }
					            try
					            {               
					                connection.close();
					            }
					            catch(IOException ioe)
					            {                
					            }
					        }
		            }
              }});
		 
           CantidadAct++;   
           try {
          	 
        	    inGlobalTime=Integer.parseInt(strTimeSender);
        	   
        	    System.out.println("LOCATION WAIT: "+String.valueOf(inGlobalTime*1000)+" ms");
        	    Thread.sleep(inGlobalTime*1000);		/////////ESPERA EL TIEMPO QUE SE CONFIGURO DE ENVIO
				//location.wait(inGlobalTime);		//TIEMPO DE ESPERA PARA VOLVER A ENVIAR
				//provider.wait(inGlobalTime);		//TIEMPO DE ESPERA PARA VOLVER A ENVIAR
				
				
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
  
	
////////////################################ READFILE & SAVEFILE ########################//////////////	
////////////////////////////////////////////////////////////////////////////////////////////////

public void saveFile(String path, String name,String DataToSave) 
{		//GUARDO DATOS EN ARCHIVO
	try {
		FileConnection fconn;
		String url = path + name;
		//System.getProperty("fileconn.dir.private");
		//  String url= System.getProperty("file:///C:/") + name;
		String string = DataToSave;
		//String string = itemEditText.getString();
		string= string+";";
		
		System.out.println("[saveFile] DATOS A GRABAR: "+string);
		
		byte data[] = string.getBytes();
		///REVISO DIRECTORIO
		
		//fconn = (FileConnection)Connector.open(System.getProperty("file:///C:/cys"), Connector.READ_WRITE);
		//fconn = (FileConnection)Connector.open("file:///C:/cys/", Connector.READ_WRITE);
		fconn = (FileConnection)Connector.open(path, Connector.READ_WRITE);
		if (!fconn.exists()) {
			fconn.mkdir();
		}   
		fconn.close();
		
		///REVISO FILE
		fconn = (FileConnection)Connector.open(url, Connector.READ_WRITE);
		// fconn = (FileConnection)Connector.open("file:///C:/cys/"+name, Connector.READ_WRITE);
		if (!fconn.exists()) {
			fconn.create();
		}
		else{
		
		//fconn.delete();
		// fconn.create();
		}
		OutputStream ops = fconn.openOutputStream();
		ops.write(data);
		ops.close();
		fconn.close();
	}
	catch (IOException ioe) {
	System.out.println("[saveFile]IOException: "+ioe.getMessage());
	}
	catch (SecurityException se) {
	System.out.println("[saveFile]Security exception:" + se.getMessage());
	}
} 
////////////####################################READ ##########################////////////////////////////
public String ReadFile(String path, String name) 
{
	String url = path + name;
	//String url= System.getProperty("file:///C:/") + name;
	
	byte[] b = new byte[60];
	String smail = null;
	try 
	{
		System.out.println("[ReadFile] DIRECTORIO LECTURA: " + url+"\n");
		
		FileConnection fconn = (FileConnection)Connector.open(url, Connector.READ);
		//FileConnection fconn = (FileConnection)Connector.open("file:///cys/", Connector.READ);
		//showConfirmation("PATH OPENED: ",url);		//DEBUG
		
		if(fconn.exists()) 
		{                              
			System.out.println("[ReadFile] EXISTE File\n");
			InputStream is=null;
			try
			{
				is = fconn.openInputStream();
			}catch(Exception ex)
			{
				return null;
			}
				is.read(b);
				is.close();    	
				fconn.close();
		}else
		{
			System.out.println("[ReadFile] No existe File");
			//showConfirmation("PATH: ",path);		//DEBUG
			return null;
		
		}
	}
	catch (IOException ioe) {
	System.out.println("[ReadFile]IOException: "+ioe.getMessage()+"\n");
	}
	catch (SecurityException se) {
	System.out.println("[ReadFile]Security exception:" + se.getMessage()+"\n");
	}

	int x=0;
	while(b[x]!=';')
	{
	
	x++;
	
	}	   
	byte[] byEmail = new byte[x];
	System.arraycopy(b,0,byEmail,0,x);
	
	smail = new String(byEmail);
	
	System.out.println("[ReadFile] FILE LEIDO: " + smail+"\n");
	return smail;

} 

	
	//////////////////////////////////////////// PERMISOS ///////////////////////////////////////////////////////////
    //////#################################################################################################
    public void voPermisos()
    {
    	
        /*permissions.addPermission( ApplicationPermissions.PERMISSION_LOCATION_DATA );
        permissions.addPermission( ApplicationPermissions.PERMISSION_APPLICATION_MANAGEMENT );
        permissions.addPermission( ApplicationPermissions.PERMISSION_EMAIL );
        permissions.addPermission( ApplicationPermissions.PERMISSION_INTERNET );
        permissions.addPermission( ApplicationPermissions.PERMISSION_SERVER_NETWORK );
        permissions.addPermission( ApplicationPermissions.PERMISSION_PHONE );
        */
    }
	
	
	
}